package as2.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import as2.model.UserService;
import as2.model.pojo.User;

// Extend HttpServlet class
public class Login extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// Method to handle GET method request.
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Set response content type
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) { /* report an error */
		}
		JSONObject jsonObject;
		String username = null;
		String password = null;
		try {
			jsonObject = new JSONObject(jb.toString());
			username = (String) jsonObject.get("username");
			password = (String) jsonObject.get("password");
		} catch (JSONException e) {
			request.getRequestDispatcher("/index.jsp").forward(request,
					response);
			return;
		}

		User user = UserService.getUser(username, password);
		if (user == null) {
			response.sendError(401);
			return;
		}

		JSONObject json = new JSONObject(user);
		String userJson = json.toString();
		out.println(userJson);
		request.getSession().setAttribute("user", userJson);
		request.getSession().setAttribute("userObj", user);
		System.out.println(userJson);
		request.getSession().setAttribute("userJson", userJson);
	}

	// Method to handle POST method request.
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}